import Food from "./Food";
import Score_pannel from "./Score_pannel";
import Snake from "./Snake";

class GameController{
    snake: Snake
    food: Food
    score_pannel:Score_pannel
    direction=''
    alive = true

    constructor(){
        this.snake = new Snake()
        this.food = new Food()
        this.score_pannel = new Score_pannel()
        this.init()
    }


    init(){
        this.food.change()
        document.addEventListener('keydown',this.set_direction)
        this.run()
    }

    set_direction = (event:KeyboardEvent)=>{
        this.direction = event.key
    }
   
    run = () =>{
        
        let s_x = this.snake.X
        let s_y = this.snake.Y
        switch (this.direction) {
            case 'ArrowDown':
                s_y += 10
                break;

            case 'ArrowLeft':
                s_x -= 10
                break;

            case 'ArrowUp':
                s_y -= 10
                break;

            case 'ArrowRight':
                s_x +=10
                break;
        }

        if(this.food.X == s_x && this.food.Y == s_y) {
            this.food.change()
            this.score_pannel.addScore()
            this.snake.addbody()
        }

      

        try{
            this.snake.X = s_x
            this.snake.Y = s_y
        }catch(e){
            alert(e.message)
            this.alive = false
        }
       
        this.alive && setTimeout(this.run,100-(Number(this.score_pannel.level.innerHTML)-1)*10)
        
    }

   

}

export default GameController